﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SchoolManagementSystem.Controls;
using DevExpress.XtraEditors;
using System.IO;
using SchoolManagementSystem.Forms;
using Helper;
using ActionServices;
using System.Reflection;
using SchoolManagementSystem.Details;
using CoreData;
namespace SchoolManagementSystem
{
    public partial class frmMaster : DevExpress.XtraEditors.XtraForm
    {
        public frmMaster()
        {
            InitializeComponent();
           
            SearchPanel.Visible = false;
            splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel2;
            CheckForIllegalCrossThreadCalls = false;
            
        }
        DetailUC _DetailUC { get; set; }
        SearchUC _SearchUC { get; set; }

        internal BaseActionService _Model;
        bool _isFirstFocus = true;
        string _searchString;
        bool _layoutRestored = false;
        string GridLayout = Application.StartupPath + "\\Layout";
        string DetailLayout = Application.StartupPath + "\\Layout";
        string pathUserLayout = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Jbart\\Layout");
        bool IsBinding = false;
        public string SearchString
        {
            get
            {
                return _searchString;
            }
            set
            {

                _searchString = value;
                if (_DetailUC != null)
                {
                    _DetailUC.SearchString = _searchString;
                }
                IsBinding = false;
                DataBind();
                //if (gridView1.RowCount > 0)
                //    gridView1.FocusedRowHandle = 0;
            }
        }

        public DetailUC DetailUCControl
        {
            get
            {
                return _DetailUC;
            }
            set
            {
                _DetailUC = value;
                dockPanel1.Controls.Add(_DetailUC);
                dockPanel1.Text = "Chi tiết " + _DetailUC.ObjectName;
                _DetailUC.Dock = DockStyle.Fill;
                _DetailUC.Master = this;
                this.Text = String.Format("Danh sách {0}", _DetailUC.ObjectName);
            }
        }
        public SearchUC SearchUC
        {
            get
            {
                return _SearchUC;
            }
            set
            {
                _SearchUC = value;
                 SearchPanel.Controls.Add(_SearchUC);
                _SearchUC.Dock = DockStyle.Fill;
                _SearchUC.Master = this;
                SearchPanel.Visible = true;
              //  splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;
            }
        }

        public int FocusedRow
        {
            get
            {
                return gridView1.FocusedRowHandle;
            }
        }

        public long SelectedID
        {
            get
            {
                try
                {
                    return long.Parse(gridView1.GetRowCellValue(FocusedRow, "ID").ToString());
                }
                catch (Exception)
                {
                    return -1;
                }
            }
        }

        public long SelectedIDCustom(string column)
        {
           
                try
                {
                    return long.Parse(gridView1.GetRowCellValue(FocusedRow, column).ToString());
                }
                catch (Exception)
                {
                    return -1;
                }
            
        }
       

        internal bool ReloadData(long ID)
        {
            IsBinding = false;
            DataBind();
            int i = 0;

            try
            {
                for (; i < gridView1.RowCount; i++)
                {
                    var tempid = long.Parse(gridView1.GetRowCellValue(i, "ID").ToString());
                    if (tempid == ID)
                    {
                        gridView1.FocusedRowHandle = i;
                    }
                }
            }
            catch (Exception)
            {

                //throw;
            }

            return i < gridView1.RowCount;
        }
        void RestoreLayout()
        {
            if (!_layoutRestored)
            {
                GridLayout = Application.StartupPath + "\\Layout\\" + _DetailUC.GetType().Name + ".GID";
                DetailLayout = Application.StartupPath + "\\Layout\\" + _DetailUC.GetType().Name + ".Detail";
                
                if (gridView1.RowCount > 0 && File.Exists(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID"))
                {
                    gridView1.RestoreLayoutFromXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID");
                    _layoutRestored = true;
                }
                else
                {           
                    if (gridView1.RowCount > 0 && File.Exists(GridLayout))
                    {
                        gridView1.RestoreLayoutFromXml(GridLayout);
                        _layoutRestored = true;
                    }
                }

                if (File.Exists(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail"))
                {
                    dockManager1.RestoreLayoutFromXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail");
                }
                else
                {
                    if (File.Exists(DetailLayout))
                        dockManager1.RestoreLayoutFromXml(DetailLayout);
                }
            }
        }
        private void SaveLayouts()
        {
            try
            {
                gridView1.SaveLayoutToXml(GridLayout);
                if (_DetailUC.MasterUC != null)
                {
                    _DetailUC.MasterUC.SaveLayouts();
                }
                dockManager1.SaveLayoutToXml(DetailLayout);

                if (!Directory.Exists(pathUserLayout))
                {
                    Directory.CreateDirectory(pathUserLayout);
                }
                gridView1.SaveLayoutToXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".GID");
                dockManager1.SaveLayoutToXml(pathUserLayout + "\\" + _DetailUC.GetType().Name + ".Detail");

                //  _detailControl.SaveLayouts();
            }
            catch (Exception)
            {

            }
        }



        void DataBind()
        {
            if (_Model != null)
            {
                if (!IsBinding)
                {
                    this.lblstatus.Caption = "Loading...";
                    this.Cursor = Cursors.WaitCursor;
                    IList<object> data = new List<object>();

                    if (!String.IsNullOrEmpty(_searchString))
                    {
                        gridControl1.DataSource = _Model.GetList(_searchString);
                    }
                    else
                    {
                        gridControl1.DataSource = _Model.GetList();
                    }
                  //  gridControl1.
                    gridControl1.RefreshDataSource();
                    RestoreLayout();
                    gridView1.ViewCaption = "Danh sách có " + gridView1.RowCount + " dòng";
                    this.Cursor = Cursors.Default;
                    this.lblstatus.Caption = "Done";


                    if (gridControl1.DataSource != null)
                    {
                        PropertyInfo[] propertyInfos;
                        propertyInfos = _DetailUC.Type.GetType().GetProperties();

                        foreach (PropertyInfo proInfo in propertyInfos)
                        {
                            AttributeCollection attributes = TypeDescriptor.GetProperties(_DetailUC.Type.GetType())[proInfo.Name].Attributes;

                            DescriptionAttribute myAttribute =
                               (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
                            if (String.IsNullOrEmpty(myAttribute.Description))
                            {
                                gridView1.Columns[proInfo.Name].Visible = false;
                            }
                            else
                            {
                                try
                                {
                                    gridView1.Columns[proInfo.Name].Caption = myAttribute.Description;
                                    gridView1.Columns[proInfo.Name].OptionsColumn.AllowEdit = false;
                                }catch{}
                            }
                            SetFormatGridColumn.Format(_Model, gridView1, proInfo.Name);
                        }
                        SetGridColumnInVisible.SetColumnInvisible(gridView1, _Model);
                    }
                    //  gridView1.GroupFooterShowMode = DevExpress.XtraGrid.Views.Grid.GroupFooterShowMode.VisibleIfExpanded;
                    //  gridView1.
                    gridView1.ExpandAllGroups();

                    if (_DetailUC.GetType() == typeof(Student_ResultUC))
                    {
                        barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                        barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    }
                    IsBinding = true;
                }
            }

        }

        public void ShowDetail()
        {
            dockPanel1.Show();
        }

        private bool DisplayDetail()
        {
            //if (FocusedRow >= 0)
            if (_DetailUC != null)
            {
               // if (_DetailUC.GetType() == typeof(Student_ResultUC))
               // {
              //      if (_DetailUC.ID == -1)
                    //{
                        //_DetailUC.ID = SelectedIDCustom("StudentID");
                   // }
               //// }
            //    else
              //  {
                    _DetailUC.ID = SelectedID;
                    
              //  }
                _DetailUC.SearchString = SearchString;

                _DetailUC.Display();

            }

            return true;
          
           
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DisplayDetail();
        }

        private void frmMaster_Load(object sender, EventArgs e)
        {
            SetupSecurity();
            DataBind();
        }

    
        public string SelectedName
        {
            get
            {
                string str = "";

                try
                {
                    str += "[" + (string)gridView1.GetRowCellValue(FocusedRow, "Code") + "]";
                }
                catch (Exception)
                {

                }
                try
                {
                    str += (string)gridView1.GetRowCellValue(FocusedRow, "Name");
                }
                catch (Exception)
                {
                }

                return str;
            }
        }


        protected void Delete()
        {
            

            if (gridView1.FocusedRowHandle < 0)
                return;

            if (XtraMessageBox.Show(String.Format("{0} {1} sẽ bị xóa khỏi hệ thống, bạn có đồng ý?", _DetailUC.ObjectName, SelectedName), String.Format("Xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    if (_DetailUC.Delete(SelectedID))
                    {
                        this.lblstatus.Caption = "Deleting...";
                        IsBinding = false;
                        XtraMessageBox.Show(String.Format("Xóa dữ liệu thành công {0} {1}", _DetailUC.ObjectName, SelectedName));
                        DataBind();

                    }
                    else
                    {
                        this.lblstatus.Caption = "Delete is failed...";
                        if (!String.IsNullOrEmpty(_DetailUC.ErrorMess))
                        {
                            XtraMessageBox.Show(_DetailUC.ErrorMess, String.Format("Lỗi khi xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            XtraMessageBox.Show(String.Format("Bạn phải xóa hết các mẫu tin con của {0} {1}", _DetailUC.ObjectName, SelectedName), String.Format("Lỗi khi xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        _DetailUC.ErrorMess = null;
                    }
                }
                catch (Exception)
                {
                    XtraMessageBox.Show(String.Format("Bạn phải xóa hết các mẫu tin con của {0} {1}", _DetailUC.ObjectName, SelectedName), String.Format("Lỗi khi xóa {0}", _DetailUC.ObjectName), MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void Add()
        {
            _DetailUC.DetailAdd();
        }

        void Export()
        {
            SaveFileDialog dlg = new SaveFileDialog();

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                gridView1.ExportToXls(dlg.FileName);
            }
        }
        private void barButtonItem_delete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Delete();
        }

        private void barButtonItem_new_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Add();
        }

        private void barButtonItem_export_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Export();
        }

        private void barButtonItem_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.ShowRibbonPrintPreview();
        }

        private void frmMaster_KeyDown(object sender, KeyEventArgs e)
        {
            PressKey(e);
          
          
        }

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {
            PressKey(e);
        }

        void PressKey(KeyEventArgs e)
        {
             if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.N:
                        _DetailUC.DetailAdd();
                        break;
                    case Keys.S:
                        _DetailUC.DetailSave();
                        break;
                    case Keys.P:
                        gridView1.ShowRibbonPrintPreview();
                        break;
                    case Keys.E:
                        Export();
                        break;
                    case Keys.C:
                         gridView1.CopyToClipboard();
                        break;
                    //case Keys.Delete: _detailControl.Delete(SelectedID);
                    //    break;
                }
            }

            if (e.KeyCode == Keys.F5)
            {
                ReloadData(-1);
            }
            else if (e.KeyCode == Keys.Delete)
                {
                    //_detailControl.Delete(SelectedID);
                    Delete();
                }
            else if(e.KeyCode == Keys.F11)
            {
                ShowDetailForm();
            }

        }

        private void barButtonItem_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ReloadData(-1);
        }


        protected void SetupSecurity()
        {
            string tag = DetailUCControl.Code;
            var userrolecheck = frmMain.UserModuleRole.FirstOrDefault(c => c.Module.Equals(tag));
            var grouprolecheck = frmMain.GroupModuleRole.FirstOrDefault(c => c.Module.Equals(tag));

            if ((userrolecheck != null && userrolecheck.Role.Contains("C")) || (grouprolecheck != null && grouprolecheck.Role.Contains("C")))
            {

                barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
               
            }
            else
            {
                barButtonItem_new.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("D")) || (grouprolecheck != null && grouprolecheck.Role.Contains("D")))
            {
                barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_delete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("P")) || (grouprolecheck != null && grouprolecheck.Role.Contains("P")))
            {
                barButtonItem_Print.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_Print.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

            if ((userrolecheck != null && userrolecheck.Role.Contains("E")) || (grouprolecheck != null && grouprolecheck.Role.Contains("E")))
            {
                barButtonItem_export.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
            else
            {
                barButtonItem_export.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

            }

        }

        void ShowDetailForm()
        {
            frmShowDetailForm frm = new frmShowDetailForm();
           
            frm.ShowDock(null, _DetailUC);
            DetailUCControl = (DetailUC)frm.Control1;
        }

        private void frmMaster_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveLayouts();
        }

        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Clicks == 2)
                ShowDetailForm();
        }

        private void xóaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void inToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.ShowRibbonPrintPreview();
        }

        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (gridView1.RowCount > 0)
            {
                  if (e.RowHandle >= 0)
                  {
                      //set mau dòng
                   //   SetGridRowColor.SetArrColor(gridView1, e.RowHandle, _Model, e.Appearance.BackColor,e.Appearance.ForeColor, e);
                  }               
            }
        }

        private void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (gridView1.RowCount > 0)
            {
                if (e.RowHandle >= 0)
                {
                    //set mau cột cho theo dõi học ph
                    SetGridColumnColor.SetColumnColor(gridView1, e.RowHandle,e.Column.FieldName, _Model, e.Appearance.BackColor, e.Appearance.ForeColor,e);
                }
            }
        }

        private void barButtonItem_Search_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if(SearchPanel.HasChildren)
                {
                    splitContainerControl1.PanelVisibility = SplitPanelVisibility.Both;
                }
            }
            catch
            {
                
            }
        }

       

      

    }
}
